import {PureComponent} from "react";
import {Input} from "antd";


export default class NumInput extends PureComponent {
  state = {}

  formatValue(value, type) {
    if (type == null) {
      type = "format";
    }
    let min = this.props.min;
    let max = this.props.max;
    if (min != null && value < min) {
      value = min;
    }
    if (max != null && value > max) {
      value = max;
    }
    this.onChange(value, this.props.data, type);
  }

  onChange(value, data) {
    if (this.props.onChange) {
      this.props.onChange(new Number(value), data, "change");
    }
    this.setState({value: new Number(value)})
  }

  componentDidMount() {
    if (this.props.defaultValue) {
      this.formatValue(this.props.defaultValue, "init");
    }
  }

  render() {
    return <Input type={"number"} onChange={e => {
      this.onChange(e.currentTarget.value, this.props.data);
    }}
                  addonBefore={this.props.addonBefore}
                  onBlur={e => this.formatValue(e.currentTarget.value)}
                  value={this.state.value}
                  min={this.props.min}
                  max={this.props.max}
    />;
  }
}
